package com.asset.dispoal.business.bsCase.service.commom;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.business.bsCase.domain.db.entity.BsCase;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.commom.utils.HttpUtils;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tech.mhuang.pacebox.core.async.AsyncTask;
import tech.mhuang.pacebox.core.async.DefaultAsyncTaskSupport;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: yf
 * @date: 2022-08-22 09:58:30
 */
@Slf4j
@Component
public class UpdateCaseAreaIdCommand {
    private String url = "https://restapi.amap.com/v3/geocode/geo";
    private String key = "9340ba66f6ee958184dfa362d679bb8e";
    private String privateKey = "54f658468e9f7bd38fa25252713269e4";
    @Autowired
    private BsCaseMapper caseMapper;

    public Result execute() {
        //查询出所有的户籍信息
        List<BsCase> caseList = caseMapper.queryBorrowerAddress();
        if (!CollectionUtils.isEmpty(caseList)) {
            //开启异步任务
            DefaultAsyncTaskSupport asyncTaskService = new DefaultAsyncTaskSupport();
            asyncTaskService.submit(new AsyncTask<List<BsCase>>() {
                @Override
                public void onSuccess(List<BsCase> result) {
                    log.info("异步更新行政编码执行成功：{}", result);
                    caseMapper.batchAreaIdstBsCase(result);
                }

                @Override
                public void onFailed(Throwable t) {
                    log.error("异步执行失败");
                }

                @Override
                public List<BsCase> execute() {
                    return caseList.stream().map(bsCase -> {
                        bsCase.setAreaId(getCodeByAddress(bsCase.getBorrowerAddress()));
                        return bsCase;
                    }).collect(Collectors.toList());
                }
            });
        }
        return Result.ok();
    }

    /**
     * 根据地址获取编码
     *
     * @return
     */
    private Integer getCodeByAddress(String address) {
        //构造请求参数
        Map<String, Object> signParamMap = new HashMap<>();
        signParamMap.put("key", key);
        signParamMap.put("address", address);

        String signParam = Joiner.on("&")
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(signParamMap);

        String result = HttpUtils.sendGet(url, signParam);
        JSONObject jsonObject = JSON.parseObject(result);
        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
        String adcode = geocodes.getJSONObject(0).getString("adcode");
        return Integer.valueOf(adcode);
    }
}
